/**
 * HistoryQueryAction.java
 * Created at 2017-2-2
 * Created by shihui
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.monitor.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.utils.RmsUtil;
import com.broadtext.rms.basic.model.TmPackSerial;
import com.broadtext.rms.basic.service.ITmCustomService;
import com.broadtext.rms.basic.service.ITmPackSerialService;
import com.broadtext.rms.monitor.service.IHistoryQueryService;
import com.broadtext.rms.system.service.ISysUserService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>
 * ClassName: HistoryQueryAction
 * </p>
 * <p>
 * Description: 历史查询控制层
 * </p>
 * <p>
 * Author: xieshuang
 * </p>
 * <p>
 * Date: 2017-06-29
 * </p>
 */
@Controller
@RequestMapping("/monitor/historyQuery")
public class HistoryQueryAction {
	/**
     * 日志信息
     */
    public static Logger logger = LoggerFactory.getLogger(HistoryQueryAction.class);
	/**
	 * 注入service
	 */
	@Autowired
	@Qualifier("historyQueryService")
	private IHistoryQueryService historyQueryService;
	
	/**
     * 注入service
     */
    @Autowired
    @Qualifier("tmPackSerialService")
    private ITmPackSerialService monitorTmPackSerialService;
    
    /**
     * 用户Service
     */
    @Autowired
    @Qualifier("sysUserService")
    private ISysUserService sysUserService;
    
    /**
     * o 注入客户service
     */
    @Autowired
    @Qualifier("tmCustomService")
    private ITmCustomService tmCustomService;
    
	/**
	 * 
	 * <p>Description: 历史数据分析查询</p>
	 * @param packCode  packCode
	 * @param startTime startTime
	 * @param endTime endTime
	 * @param type type
	 * @return data
	 */
	@RequestMapping(value="/getHistoryChartData.mvc")
	@ResponseBody
	public Object getHistoryChartData(@RequestParam("packCode")String packCode, @RequestParam("startTime")String startTime,
			@RequestParam("endTime") String endTime, @RequestParam("type") String type){
		Map<String, Object> paramsMap;
		paramsMap = new HashMap<String, Object>();
		paramsMap.put("packCode", packCode);
		paramsMap.put("startTime", startTime);
		paramsMap.put("endTime", endTime);
		paramsMap.put("type", type);
		try {
			return this.historyQueryService.getHistoryChartData(paramsMap);
		} catch (DaoException e) {
			logger.error("查询出错：", e);
			return null;
		}
	}
	
	 /**
     * 
     * <p>Description: 导出历史数据</p>
     * @param packCode  packCode
     * @param startTime startTime
     * @param endTime  endTime
     * @param option  value="0">SOC  value="1">总电压  value="2">总电流 value="3">单体最高温度  value="4">单体温度与温差 value="5">单体电压与压差
     * @param response 响应
     * @throws IOException 异常
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/export.mvc")
    public void exportLog(@RequestParam("packCode")String packCode,
    		@RequestParam("startTime")String startTime,
    		@RequestParam("endTime") String endTime,
    		@RequestParam("option") String option,
    		HttpServletResponse response) throws IOException, DaoException{
    	
    	/*
    	 * 构建动态map,进行excel导出  共六种
    	 */
    	String fileName = "历史数据";
    	String title = "";
    	List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
    	//构造方法 列head   列对应字段名      列宽
        entity.add(new ExcelExportEntity("采集终端ID", "colClientId", 15));
        entity.add(new ExcelExportEntity("电池ID", "packCode", 20));
        entity.add(new ExcelExportEntity("采集时间", "gatherTime", 25));
        if("0".equals(option)){
        	entity.add(new ExcelExportEntity("soc(%)", "soc"));
        	fileName = fileName.concat("_soc");
        	title = "soc";
        }
        if("1".equals(option)){
        	entity.add(new ExcelExportEntity("总电压(V)", "totalVol"));
        	fileName = fileName.concat("_总电压");
        	title = "总电压";
        }
        if("2".equals(option)){
        	entity.add(new ExcelExportEntity("总电流(A)", "totalCurrent"));
        	fileName = fileName.concat("_总电流");
        	title = "总电流";
        }
        if("3".equals(option)){
        	entity.add(new ExcelExportEntity("单体最高温度(°C)", "maxTemp", 15));
        	fileName = fileName.concat("_单体最高电压");
        	title = "单体最高电压";
        }
        if("4".equals(option)){
        	entity.add(new ExcelExportEntity("单体最高温度(°C)", "maxTemp", 15));
            entity.add(new ExcelExportEntity("单体最低温度(°C)", "minTemp", 15));
            entity.add(new ExcelExportEntity("温差(°C)", "tempDiff"));
            fileName = fileName.concat("_单体温度与温差");
            title = "单体温度与温差";
        }
        if("5".equals(option)){
        	entity.add(new ExcelExportEntity("单体最高电压(V)", "maxVol", 15));
            entity.add(new ExcelExportEntity("单体最低电压(V)", "minVol", 15));
            entity.add(new ExcelExportEntity("压差(V)", "volDiff", 15));
            fileName = fileName.concat("_单体电压与压差");
            title = "单体电压与压差";
        }
        /*
         * 封装查询条件进map
         */
    	Map<String, Object> params;
    	params = new HashMap<String, Object>();
    	params.put("packCode", packCode);
    	params.put("startTime", startTime);
    	params.put("endTime", endTime);
    	params.put("option", option);
    	List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    	list = this.historyQueryService.findExportHistoryDataList(params);
    	
    	//调用导出方法进行excel导出
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(
        		title, title), entity, list);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        workbook.write(bao);
        RmsUtil.exportExcel(fileName.concat(".xls"), response, bao);
        bao.close();
    }
    
    /**
     * 
     * <p>Description: 电池下拉框异步加载</p>
     * @param res 请求
     * @return 结果集
     */
    @RequestMapping(value="/getPackCodeOptions.mvc")
    @ResponseBody
    public Object getPackCodeOptions(HttpServletRequest res){
    	//分页
    	PageBounds pageBounds;
        pageBounds = new PageBounds();
        //查询条件
    	String name = res.getParameter("name");  
        Integer offset = Integer.valueOf(res.getParameter("offset"));  
        Integer page = Integer.valueOf(res.getParameter("page"));  
        if (page == 1) {  
            page = 0;  
        } else {  
            page = (page - 1) * offset;  
        }
        pageBounds.setLimit(offset);
        pageBounds.setPage(page);
        Map<String, Object> params;
        params = new HashMap<String, Object>();
        params.put("name", name);
        EntityPageBean<TmPackSerial> pageBean;
        Map<String, Object> dataMap=new HashMap<String, Object>();
		try {
			pageBean = this.monitorTmPackSerialService.getPackCodeOptions(params, pageBounds);
			dataMap.put("total", pageBean.getiTotalRecords());
	        dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
	        dataMap.put("data", pageBean.getResults());
		} catch (DaoException e) {
			logger.error("查询出错：", e);
			return null;
		}
        return dataMap;  
    }
    
    /**
     * 
     * <p>Description: 电池下拉框异步加载</p>
     * @param res 请求
     * @return 结果集
     */
    @RequestMapping(value="/getPackCodeOptions2.mvc")
    @ResponseBody
    public Object getPackCodeOptions2(HttpServletResponse response,HttpServletRequest request){
        Map<String, Object> params;
        params = new HashMap<String, Object>();
      //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
        Map<String, Object> checkMap;
        List<String> list;
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                params.put("cusId", checkMap.get("cusId"));
                //查询当前登录用户所有下属子节点pk_id
                list = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                params.put("ids", list);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        //分页
        PageBounds pageBounds;
        pageBounds = new PageBounds();
        //查询条件
        String name = request.getParameter("name");  
        Integer offset = Integer.valueOf(request.getParameter("offset"));  
        Integer page = Integer.valueOf(request.getParameter("page"));  
        if (page == 1) {  
            page = 0;  
        } else {  
            page = (page - 1) * offset;  
        }
        pageBounds.setLimit(offset);
        pageBounds.setPage(page);
        params.put("name", name);
        EntityPageBean<Object> pageBean;
        Map<String, Object> dataMap=new HashMap<String, Object>();
        try {
            pageBean = this.monitorTmPackSerialService.getPackCodeOptions2(params, pageBounds);
            dataMap.put("total", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("data", pageBean.getResults());
        } catch (DaoException e) {
            logger.error("查询出错：", e);
            return null;
        }
        return dataMap;  
    }

}
